<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Logics\SmsLogic;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Logics\GoodsLogic;
use Illuminate\Support\Facades\Storage;


class GoodsController extends BaseController
{
    use HasResourceActions;


    private function getInstance(){
        static $ob=null;
        if($ob===null){
            $ob=new GoodsLogic();
        }
        return $ob;
    }
    //待提交，或驳回的商品列表
    public function noSubmitGoodsList()
    {

        return $this->goodsList(1);
    }

    //待审核商品列表
    public function checkGoodsList()
    {


        return $this->goodsList(2);
    }

    //上架商品列表
    public function upGoodsList()
    {

        return $this->goodsList(3);
    }

    //待审核商品
    public function downGoodsList()
    {

        return $this->goodsList(4);
    }

    //全部商品列表
    public function goodsList($type = 100)
    {

        $page = (int)request("page", 1);
        $per_page = (int)request("per_page", 20);
        $is_putaway = (int)request("is_putaway", -1);
        $brand_id = (int)request('brand_id', 0);
        $cha_id = (int)request('cha_id', 0);
        $goods_name = request('goods_name');
        $goods_id = (int)request('goods_id');
        $start_time = request('start_time');
        $end_time = request('end_time');

        $para=[
            'page'=>$page,
            'per_page'=>$per_page,
            'is_putaway'=>$is_putaway,
            'brand_id'=>$brand_id,
            'cha_id'=>$cha_id,
            'goods_name'=>$goods_name,
            'goods_id'=>$goods_id,
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'type'=>$type
        ];

        $ob= $this->getInstance();
        $data=$ob->getGoodsList($para);

        if ($type == 1) {
            $content = view("admin.goods.noSubmitGoodsList", $data);
        } elseif ($type == 2) {
            $content = view("admin.goods.checkGoodsList", $data);
        } elseif ($type == 3) {
            $content = view("admin.goods.upGoodsList", $data);
        } elseif ($type == 4) {
            $content = view("admin.goods.downGoodsList", $data);
        } else {
            $content = view("admin.goods.allGoodsList",$data);
        }
        $data = [
            'content' => $content,
            'header' => '商品列表',
        ];
        return $this->baseList($data);
    }

    /** 属性sku选择
     * @param int $goods_id
     * @param int $key
     * @param array $key_ar
     * @return string
     */
    function skuSelect(int $goods_id,int $key,array $key_ar){
        $count=DB::table('goods')->where('goods_id',$goods_id)->count();
        if(empty($count)){
            return '参数有误';
        }
        $attr_type_ids=DB::table('attr_type')->where('goods_id',$goods_id)->pluck('attr_id');
        $attr_type_ids=ob_to_array($attr_type_ids);
        $attr_val=DB::table('attr_val')->whereIn('attr_id',$attr_type_ids)->select('attr_id','id')->get();
        $attr_val=ob_to_array($attr_val);
        $attr=[];
        $attr_ar=[];
        foreach($attr_val as $v){
            $attr[$v['attr_id']][]=$v['id'];
            $attr_ar[]=$v['id'];
        }
        $sku=DB::table('goods_sku')->where('goods_id',$goods_id)->pluck('sku');
        $skus=ob_to_array($sku);
        $sku=[];$sku_ar=[];
        foreach($skus as $v){
            $r=$v?explode(',',$v):[];
            $sku[]=$r;
            $sku_ar=array_merge($sku_ar,$r);
        }
        if(!in_array($key,$sku_ar)){
            return '参数有误';
        }
        if(!in_array($key,$key_ar)){
            return '参数有误';
        }

        //禁选属性
        $jingxuan_ar=array_diff($attr_ar,$sku_ar);

        $p=0;
        foreach($sku as $v){
            $jiao_ar=array_intersect($v,$key_ar);
            if(count($jiao_ar)==count($key_ar)){
                $p=1;break;
            }
        }
        if($p==0){
            $key_ar=[$key];
        }

        $kexuan_ar=[];//可选属性
        foreach($sku as $v){
            $jiao_ar=array_intersect($v,$key_ar);
            if(count($jiao_ar)==count($key_ar)){
                $kexuan_ar=array_merge($kexuan_ar,$v);
            }
        }

        foreach($attr as $v){
            $jiao_ar=array_intersect($v,$key_ar);
            if($jiao_ar){
                $kexuan_ar=array_merge($kexuan_ar,$v);
            }
        }

        $a=array_diff($sku_ar,$kexuan_ar);
        $jingxuan_ar=array_merge($jingxuan_ar,$a);
        $jingxuan_ar=array_unique($jingxuan_ar);

        $kexuan_ar=array_diff($kexuan_ar,$jingxuan_ar);
        $kexuan_ar=array_diff($kexuan_ar,$key_ar);
        $kexuan_ar=array_unique($kexuan_ar);
        sort($kexuan_ar);

        p($key_ar); //已选属性
        p($jingxuan_ar);
        p($kexuan_ar);die;

    }


    //商品添加
    public function goodsAdd()
    {
        if ($_POST) {
            $supplier_id = (int)request('supplier_id');
            $brand_id = (int)request("brand_id");
            $cate_id = (int)request("cate_id");
            $goods_name = trim(request('goods_name'));
            $keyword = trim(request('keyword'));
            $detail = trim(request('detail'));
            $goods_sale_phone = trim(request('goods_sale_phone'));
            $goods_price = trim(request('goods_price'));
            $goods_official_price = trim(request('goods_official_price'));
            $goods_purchase_price = trim(request('goods_purchase_price'));
            $is_required = (int)request('is_required');
            $goods_installation_charge = trim(request('goods_installation_charge'));
            $goods_installation_show = trim(request('goods_installation_show'));
            $is_required_insurance = (int)request('is_required_insurance');
            $goods_insurance = trim(request('goods_insurance'));
            $goods_tenancy_term = request('goods_tenancy_term');

            $goods_price = (float)str_replace(',', '', $goods_price);
            $goods_official_price = (float)str_replace(',', '', $goods_official_price);
            $goods_purchase_price = (float)str_replace(',', '', $goods_purchase_price);
            $goods_installation_charge = (float)str_replace(',', '', $goods_installation_charge);
            $goods_insurance = (float)str_replace(',', '', $goods_insurance);

            $para=[
                'supplier_id'=>$supplier_id,
                'brand_id'=>$brand_id,
                'cate_id'=>$cate_id,
                'goods_name'=>$goods_name,
                'keyword'=>$keyword,
                'detail'=>$detail,
                'goods_sale_phone'=>$goods_sale_phone,
                'goods_price'=>$goods_price,
                'goods_official_price'=>$goods_official_price,
                'goods_purchase_price'=>$goods_purchase_price,
                'is_required'=>$is_required,
                'goods_installation_charge'=>$goods_installation_charge,
                'goods_installation_show'=>$goods_installation_show,
                'is_required_insurance'=>$is_required_insurance,
                'goods_insurance'=>$goods_insurance,
                'goods_tenancy_term'=>$goods_tenancy_term
            ];

            $ob=$this->getInstance();
            $data=$ob->goodsAdd($para);
            $this->result($data);
        }

        $ob=$this->getInstance();
        $data=$ob->getGoodsAdd();
        $content = view("admin.goods.goodsAdd", $data);
        $data = [
            'content' => $content,
            'header' => '添加商品',
        ];
        return $this->baseList($data);
    }

    //商品编辑
    public function goodsEdit()
    {
        if ($_POST) {
            $supplier_id = (int)request('supplier_id');
            $brand_id = (int)request("brand_id");
            $cate_id = (int)request("cate_id");
            $goods_name = trim(request('goods_name'));
            $keyword = trim(request('keyword'));
            $detail = trim(request('detail'));
            $goods_sale_phone = trim(request('goods_sale_phone'));
            $goods_price = trim(request('goods_price'));
            $goods_official_price = trim(request('goods_official_price'));
            $goods_purchase_price = trim(request('goods_purchase_price'));
            $is_required = (int)request('is_required');
            $goods_installation_charge = trim(request('goods_installation_charge'));
            $goods_installation_show = trim(request('goods_installation_show'));
            $is_required_insurance = (int)request('is_required_insurance');
            $goods_insurance = trim(request('goods_insurance'));
            $goods_id = (int)request('goods_id');
            $goods_tenancy_term = request('goods_tenancy_term');

            $goods_price = (float)str_replace(',', '', $goods_price);
            $goods_official_price = (float)str_replace(',', '', $goods_official_price);
            $goods_purchase_price = (float)str_replace(',', '', $goods_purchase_price);
            $goods_installation_charge = (float)str_replace(',', '', $goods_installation_charge);
            $goods_insurance = (float)str_replace(',', '', $goods_insurance);

            $para=[
                'supplier_id'=>$supplier_id,
                'brand_id'=>$brand_id,
                'cate_id'=>$cate_id,
                'goods_name'=>$goods_name,
                'keyword'=>$keyword,
                'detail'=>$detail,
                'goods_sale_phone'=>$goods_sale_phone,
                'goods_price'=>$goods_price,
                'goods_official_price'=>$goods_official_price,
                'goods_purchase_price'=>$goods_purchase_price,
                'is_required'=>$is_required,
                'goods_installation_charge'=>$goods_installation_charge,
                'goods_installation_show'=>$goods_installation_show,
                'is_required_insurance'=>$is_required_insurance,
                'goods_insurance'=>$goods_insurance,
                'goods_id'=>$goods_id,
                'goods_tenancy_term'=>$goods_tenancy_term
            ];
            $ob=$this->getInstance();
            $data=$ob->goodsEdit($para);
            $this->result($data);
        }

        $goods_id=(int)request('goods_id');
        $ob=$this->getInstance();
        $data=$ob->getGoodsEdit($goods_id);
        $content = view("admin.goods.goodsEdit", $data);
        $data = [
            'content' => $content,
            'header' => '编辑商品',
        ];
        return $this->baseList($data);
    }

    //商品信息展示
    public function goodsShow()
    {
        $goods_id = (int)request('goods_id');
        $ob=$this->getInstance();
        $data = $ob->goodsShow($goods_id);
        if ($data && is_string($data)) die(json_error($data));
        $content = view("admin.goods.goodsShow", $data);
        $data = [
            'content' => $content,
            'header' => '商品查看',
        ];
        return $this->frameList($data);
    }


    //添加商品图片
    public function goodsAddImg(Request $request)
    {
        if ($_POST) {
            $goods_id = (int)request('goods_id');
            $id = (int)request('id');
            $type = trim(request('type'));
            $action = trim(request('action'));
            $img_type = (int)request('img_type');

            $para=[
                'goods_id'=>$goods_id,
                'id'=>$id,
                'type'=>$type,
                'action'=>$action,
                'img_type'=>$img_type
            ];
            $ob=$this->getInstance();
            $data=$ob->goodsAddImg($request,$para);
            $this->result($data);
        }

        $goods_id = (int)request("goods_id");
        $ob=$this->getInstance();
        $data=$ob->getGoodsAddImg($goods_id);
        $this->error($data);
        $content = view("admin.goods.goodsAddImg", $data);
        $data = [
            'content' => $content,
            'header' => '添加商品图片',
        ];
        return $this->baseList($data);
    }

    //商品租期展示
    public function goodsLease()
    {
        $goods_id = (int)request('goods_id');
        $ob= $this->getInstance();
        $data = $ob->goodsLease($goods_id);
        if ($data && is_string($data)) die(json_error($data));
        $content = view("admin.goods.goodsLease", $data);
        $data = [
            'content' => $content,
            'header' => '商品租期展示',
        ];
        return $this->baseList($data);
    }

    //商品租期设置
    public function goodsLeaseSet()
    {
        if ($_POST) {
            $goods_id = (int)request('goods_id');
            $sku = (int)request('sku', 0);
            $rent_price = request('rent_price');
            $deposit_price = request('deposit_price');
            $buyout_price = request('buyout_price');
            $term_num = (int)request('term_num');
            $price = request('price') ?: [];
            $day_num = request('day_num') ?: [];

            $rent_price = (float)str_replace(',', '', $rent_price);
            $deposit_price = (float)str_replace(',', '', $deposit_price);
            $buyout_price = (float)str_replace(',', '', $buyout_price);

            $para=[
                'goods_id'=>$goods_id,
                'sku'=>$sku,
                'rent_price'=>$rent_price,
                'deposit_price'=>$deposit_price,
                'buyout_price'=>$buyout_price,
                'term_num'=>$term_num,
                'price'=>$price,
                'day_num'=>$day_num
            ];
            $ob=$this->getInstance();
            $data=$ob->goodsLeaseSet($para);
            $this->result($data);
        }

        $goods_id = (int)request('goods_id');
        $ob=$this->getInstance();
        $data=$ob->getGoodsLease($goods_id);
        if($data && is_string($data)) die(json_error($data));
        $content = view("admin.goods.goodsLeaseSet", $data);
        $data = [
            'content' => $content,
            'header' => '商品租期设置',
        ];
        return $this->baseList($data);
    }

    //商品租期编辑
    public function goodsLeaseEdit()
    {
        if ($_POST) {
            $goods_id = (int)request('goods_id');
            $id = (int)request('id');
            $sku = (int)request('sku', 0);
            $rent_price = request('rent_price');
            $deposit_price = request('deposit_price');
            $buyout_price = request('buyout_price');
            $term_num = (int)request('term_num');
            $price = request('price') ?: [];
            $day_num = request('day_num') ?: [];

            $rent_price = (float)str_replace(',', '', $rent_price);
            $deposit_price = (float)str_replace(',', '', $deposit_price);
            $buyout_price = (float)str_replace(',', '', $buyout_price);

            $para=[
                'goods_id'=>$goods_id,
                'sku'=>$sku,
                'rent_price'=>$rent_price,
                'deposit_price'=>$deposit_price,
                'buyout_price'=>$buyout_price,
                'term_num'=>$term_num,
                'price'=>$price,
                'day_num'=>$day_num,
                'id'=>$id
            ];
            $data=GoodsLogic::goodsLeaseEdit($para);
            $this->result($data);
        }

        $id = (int)request('id');
        $ob=$this->getInstance();
        $data=$ob->getGoodsLeaseById($id);
        if($data && is_string($data)) die(json_error($data));
        $content = view("admin.goods.goodsLeaseEdit", $data);
        $data = [
            'content' => $content,
            'header' => '商品租期编辑',
        ];
        return $this->baseList($data);
    }


    //商品参数
    public function goodsAttr()
    {
        if ($_POST) {
            $goods_id = (int)request('goods_id');
            $name = request('name');
            $val = request('val');
            $para=[
                'goods_id'=>$goods_id,
                'name'=>$name,
                'val'=>$val
            ];
            $ob=$this->getInstance();
            $data=$ob->goodsAttrAdd($para);
            $this->result($data);
        }

        $goods_id = (int)request('goods_id');
        $ob=$this->getInstance();
        $data= $ob->getGoodsAttr($goods_id);
        if($data && is_string($data)) die(json_error($data));
        $content = view("admin.goods.goodsAttr", $data);
        $data = [
            'content' => $content,
            'header' => '添加商品规格参数',
        ];
        return $this->baseList($data);
    }

    //商品销售属性
    public function sku()
    {
        if ($_POST) {
            $goods_id = (int)request('goods_id');
            $id = (int)request('id', 0);
            $zhi = $_POST['zhi'] ?? [];
            $newattr = trim(request('newattr', ''));

            $para=[
                'goods_id'=>$goods_id,
                'id'=>$id,
                'zhi'=>$zhi,
                'newattr'=>$newattr
            ];
            $ob=$this->getInstance();
            $data=$ob->skuAdd($para);
            $this->result($data);
        }

        $goods_id = (int)request('goods_id');
        $ob=$this->getInstance();
        $data=$ob->getSkuByGoodsId($goods_id);
        if($data && is_string($data)) die(json_error($data));
        $content = view("admin.goods.sku", $data);
        $data = [
            'content' => $content,
            'header' => '添加商品规格参数',

        ];
        return $this->baseList($data);
    }

    //设置商品sku
    public function goodsSku()
    {
        $goods_id = (int)request('goods_id');
        $ob=$this->getInstance();
        $data=$ob->goodsSku($goods_id);
        if($data && is_string($data)) die(json_error($data));

        $content = view("admin.goods.goodsSku", $data);
        $data = [
            'content' => $content,
            'header' => '商品SKU设置',

        ];
        return $this->baseList($data);
    }



    //修改一组商品的SKU
    public function goodsSkuEdit()
    {
        if ($_POST) {
            $goods_id = (int)request('goods_id');
            $id = (int)request('id');
            $sku = $_POST['sku'];
            $goods_price = trim(request('goods_price'));
            $goods_official_price = trim(request('goods_official_price'));
            $goods_purchase_price = trim(request('goods_purchase_price'));
            $goods_price = (float)str_replace(',', '', $goods_price);
            $goods_official_price = (float)str_replace(',', '', $goods_official_price);
            $goods_purchase_price = (float)str_replace(',', '', $goods_purchase_price);

            $para=[
                'goods_id'=>$goods_id,
                'sku'=>$sku,
                'goods_price'=>$goods_price,
                'goods_official_price'=>$goods_official_price,
                'goods_purchase_price'=>$goods_purchase_price,
                'id'=>$id
            ];

            $ob=$this->getInstance();
            $data=$ob->goodsSkuEdit($para);
            $this->result($data);
        }

        $id = (int)request('id');
        $ob=$this->getInstance();
        $data=$ob->getGoodsSkuById($id);
        if($data && is_string($data)) die(json_error($data));
        $content = view("admin.goods.goodsSkuEdit", $data);
        $data = [
            'content' => $content,
            'header' => '商品SKU编辑',
        ];
        return $this->baseList($data);
    }



    public function testUpload(Request $request){
        if($_POST){
            p($_FILES);
        }
        $url =  config('sys.sms_send_url');

        echo base64_encode(json_encode(['code'=>'1234']));die;
        $post_data = [
            'phone' =>'13253602577',
            'data_param'=>base64_encode(json_encode(['code'=>'1234'])),
            'type'=>4
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if(strpos($url,'https')!==false){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);


        if(empty($output)) return ['status'=>1002,'msg'=>'失败'];
        return  json_decode($output,true);

        $content = view("admin.goods.testUpload");
        $data = [
            'content' => $content,
            'header' => '图片上传测试',
        ];
        return $this->baseList($data);
    }





}